import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:webview_flutter/webview_flutter.dart';

///带加载进度条的webView
class ProgressWebView extends StatefulWidget {
  final String initialUrl;
  final WebViewCreatedCallback onWebViewCreated;
  final NavigationDelegate navigationDelegate;
  final PageFinishedCallback onPageFinished;
  final bool injectFontFamily;

  const ProgressWebView(
      {Key key,
      this.initialUrl,
      this.onWebViewCreated,
      this.navigationDelegate,
      this.onPageFinished,
      this.injectFontFamily = true})
      : super(key: key);

  @override
  _ProgressWebViewState createState() => _ProgressWebViewState();
}

class _ProgressWebViewState extends State<ProgressWebView> {
  @override
  Widget build(BuildContext context) {
    return new Stack(
      alignment: Alignment.center,
      children: _buildWebView(context),
    );
  }

  ///webView 加载中
  bool showLoading = false;
  WebViewController _controller;

  List<Widget> _buildWebView(BuildContext context) {
//    var _url = widget.initialUrl;
//    _url =  Utf8Decoder().convert(_url.codeUnits);
//    try {
//      var map = Uri.splitQueryString(_url);
//      print("$map");
//      _url = Uri.encodeFull(Uri.decodeFull(_url));
//    } catch (e) {}
//
//    var loadUrl = _url;
    var widgets = <Widget>[
      new WebView(
          initialUrl: widget.initialUrl,
          debuggingEnabled: true,
          onPageStarted: (url) {
            setState(() {
              showLoading = true;
            });
            debugPrint("开始加载---->$url");
            if (widget.injectFontFamily)
              rootBundle.load("assets/fonts/FZBiaoYS_GBK_YS.ttf").then((value) {
                var base64String = base64Encode(value.buffer.asUint8List());
                _controller.evaluateJavascript("javascript:!function(){" +
                    "s=document.createElement('style');s.innerHTML=" +
                    "\"@font-face{font-family:myhyqh;src:url(data:font/truetype;charset=utf-8;base64,$base64String)format('truetype');}*{font-family:myhyqh !important;}\";" +
                    "document.getElementsByTagName('head')[0].appendChild(s);" +
                    "document.getElementsByTagName('body')[0].style.fontFamily = \"myhyqh\";}()");
              });
          },
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (controller) {
            _controller = controller;
            widget.onWebViewCreated(controller);
          },
          navigationDelegate: widget.navigationDelegate,
          onPageFinished: (url) {
            debugPrint("加载成功，隐藏进度条 $url");
            setState(() {
              showLoading = false;
            });
            if (null != widget.onPageFinished) {
              widget.onPageFinished(url);
            }
          },
          gestureNavigationEnabled: true,
          initialMediaPlaybackPolicy: AutoMediaPlaybackPolicy.always_allow)
    ];

    widgets.add(new Visibility(
      child: SizedBox(
        child: CircularProgressIndicator(
          backgroundColor: Colors.deepOrange,
          valueColor: new AlwaysStoppedAnimation<Color>(Colors.grey),
        ),
        height: 35.0,
        width: 35.0,
      ),
      visible: showLoading,
    ));
    return widgets;
  }
}
